package com.atguigu.guli.gateway.execept;

import com.google.gson.JsonObject;
import javassist.NotFoundException;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.web.reactive.function.server.*;

import java.util.HashMap;
import java.util.Map;

public class GoldException extends DefaultErrorWebExceptionHandler {
    public GoldException(ErrorAttributes errorAttributes, ResourceProperties resourceProperties, ErrorProperties errorProperties, ApplicationContext applicationContext) {
        super(errorAttributes, resourceProperties, errorProperties, applicationContext);
    }

    @Override
    protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
        return RouterFunctions.route(RequestPredicates.all(),this::renderErrorResponse);
    }

    @Override
    protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
        Map<String, Object> map = new HashMap<>();
        map.put("code",200);//前端项目判断请求是否成功，所有的响应报文状态码都是200，在响应体中的R对象的code值中设置错误状态码
        map.put("message" , "出现异常");
        JsonObject jsonObject = new JsonObject();
        Throwable error = getError(request);//根据request对象获取错误对象
        int code = 30001;//网关项目通用错误
        if(error instanceof NotFoundException){
            code = 30002;//注册中心找不到目标微服务的异常
        }
        Map<String, Object> map2 = new HashMap<>();
        map2.put("code" ,code );
        map2.put("message" , error.getMessage());
        map2.put("success" , false);
//        jsonObject.addProperty("data" , null);

        map.put("data" , map2);//设置响应体内容： 本次错误的R对象的json字符串
        return map;
    }

    @Override
    protected int getHttpStatus(Map<String, Object> errorAttributes) {
        return 200;
    }
}
